在路由上定義好接收的路徑參數名稱 ex: /:id
修改 app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StoreComponent } from './store/store.component';
import { RoleComponent } from './role/role.component';
const routes: Routes = [
{ path: 'store', component: StoreComponent },
{ path: 'role', component: RoleComponent },
{ path: 'role/:id', component: RoleComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
修改role.component.ts
...
constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
console.log(this.route.snapshot.paramMap.get('id'));
}
http://localhost:4200/role/6556
當帶入路徑參數時,
可透過route.snapshot.paramMap.get('id')
取得變數id
修改 role.component.ts
...
export class RoleComponent implements OnInit {
atk = 0;
def = 0;
constructor(private route: ActivatedRoute, private router: Router) {
}
ngOnInit(): void {
this.route.queryParams.subscribe(
params => {
this.atk = params['atk'];
this.def = params['def'];
}
)
}
}
修改 role.component.html
<div>勇者,你的攻擊力為:{{atk}}</div>
<div>勇者,你的防禦力:{{def}}</div>
http://localhost:4200/role?atk=15&def=6
當帶入查詢參數時,
可透過route.queryParams
取得key、value對應物件的參數